package com.sunb2b.web.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;

import com.sunb2b.dao.MemberDAO;
import com.sunb2b.dao.UserDAO;
import com.sunb2b.entity.CompanyMember;
import com.sunb2b.entity.Member;
import com.sunb2b.entity.PersonMember;
import com.sunb2b.entity.Product;
import com.sunb2b.entity.User;
import com.sunb2b.pojo.PageSearchResult;
import com.sunb2b.service.MemberService;
import com.sunb2b.service.ProductService;
import com.sunb2b.service.UserService;
import com.sunb2b.web.form.LoginForm;
import com.sunb2b.web.form.MemberSearchForm;
import com.sunb2b.web.pojo.MemberJson;
import com.sunb2b.web.util.Constants;
import com.sunb2b.web.util.Message;

@Controller
public class AdminController {
	
	private static final Logger log = LoggerFactory.getLogger(AdminController.class);
	
	@Inject 
    private MemberService memberService;
	
	@Inject
	private UserService userService;
	
	@Inject
	private ProductService productService;
    
    @RequestMapping(value="/admin", method=RequestMethod.GET)
    public String adminHome(){
        // do entitlement check here
        return "admin/index";
    }
    
    @RequestMapping(value="/admin/welcome", method=RequestMethod.GET)
    public String welcome(){
        return "admin/welcome";
    }
    
    @RequestMapping(value="/admin/login", method=RequestMethod.GET)
    public String login(@ModelAttribute("loginForm") LoginForm loginForm){
        return "admin/login";
    }
    
    @RequestMapping(value="/admin/member/enterpriseUser", method=RequestMethod.GET)
    public String getEnterpriseUserPage(){
        return "admin/member/enterpriseUser";
    }
    
    @RequestMapping(value="/admin/member/personalUser", method=RequestMethod.GET)
    public String getPersonalUserPage(){
        return "admin/member/personalUser";
    }
    
    @RequestMapping(value="/admin/member/systemUser", method=RequestMethod.GET)
    public String getSystemUserPage(){
        return "admin/member/systemUser";
    }
    
    @RequestMapping(value="/admin/login", method=RequestMethod.POST)
    public String validate(@Valid LoginForm loginForm, BindingResult result, WebRequest request, HttpServletRequest httprequest, Model model){
        System.out.println("validating user...");
    	System.out.println("userName:"+loginForm.getName());
    	System.out.println("passoword:"+loginForm.getPassword());
        
    	String userName = loginForm.getName();
    	String password = loginForm.getPassword();
    	
        if (result.hasErrors()) {
            return "admin/login";
        }
    	
    	List<User> users = userService.getUserByUserName(userName);
    	if(users == null || users.size() == 0){
    		System.out.println("User doesn't exist!");
    		model.addAttribute("message", "用户不存在.");
    		return "admin/login";
    	}else{
    		for(User user : users){
    			if(password.equals(user.getPassword())){
    				if("Active".equalsIgnoreCase(user.getStatus())){
        				System.out.println("User Validation passed.");
        				httprequest.getSession().setAttribute("user",user);
        				continue;
    				}else{
        	    		model.addAttribute("message", "用户不可用.");
        	    		return "admin/login";
    				}
    			}else{
    				System.out.println("Password not right!");
    	    		model.addAttribute("message", "密码有误.");
    	    		return "admin/login";
    			}
    		}
    	}
    	return "admin/main";
    }
    
    @RequestMapping(value="/admin/logout", method=RequestMethod.GET)
    public String logout(HttpServletRequest request, @ModelAttribute("loginForm") LoginForm loginForm){
    	request.getSession().invalidate();
    	return "admin/login";
    }
    
    @RequestMapping(value="/admin/member/query", method=RequestMethod.POST)
    public String query(@Valid MemberSearchForm form, WebRequest request, HttpServletResponse response, Model model){
    	//System.out.println("####### come to here");
    	
    	MemberJson jsonwrapper = new MemberJson();
    	
    	DetachedCriteria dc = null;
    	
    	if(form.getType().equals("person")){
    		dc = DetachedCriteria.forClass(PersonMember.class);
    		
    		PageSearchResult rs = memberService.search(dc, form.getPage(), form.getPageSize());
        	System.out.println("result size:"+rs.getTotal()+"|"+rs.getItems().size());
        	
    	   	jsonwrapper.setTotal(rs.getTotal());
        	jsonwrapper.setRows(rs.getMemberList());
    	}
    	else if(form.getType().equals("company")){
    		dc = DetachedCriteria.forClass(CompanyMember.class);
    		PageSearchResult rs = memberService.search(dc, form.getPage(), form.getPageSize());
        	System.out.println("result size:"+rs.getTotal()+"|"+rs.getItems().size());
    	   	jsonwrapper.setTotal(rs.getTotal());
        	jsonwrapper.setRows(rs.getMemberList());
        	
    	}
    	else if(form.getType().equals("system")){
    		dc = DetachedCriteria.forClass(User.class);
    		PageSearchResult rs = userService.search(dc, form.getPage(), form.getPageSize());
    		jsonwrapper.setTotal(rs.getTotal());
    		jsonwrapper.setRows(rs.getSystemAdminList());
    	}
    	else{
    		throw new RuntimeException("Unsupported type!!!");
    	}
    	
    	//if(form.getRegionId()!=null){
    		//dc.add(Restrictions.like("regionId", form.getRegionId(), MatchMode.START));
    	//}
    	//System.out.println("PageSearchResult : "+rs.getMemberList());
    	
    	
 
    	
    	ObjectMapper mapper = new ObjectMapper();
    	
    	try {
    		String jsonResult = mapper.writeValueAsString(jsonwrapper);
    		
    		System.out.println("jsonResult:"+jsonResult);
			response.getWriter().write(jsonResult);
			response.getWriter().flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
    	//model.addAttribute("results", rs);
		return null;
    }
    
    @RequestMapping(value="/admin/member/update", method=RequestMethod.POST)
    public void updateMember(WebRequest request, HttpServletResponse response){
    	String membertype = request.getParameter("membertype");
    	String memberaction = request.getParameter("memberaction");
    	String ids = request.getParameter("ids");
    	//String password = request.getParameter("password");
    	
    	System.out.println("membertype:"+membertype);
    	System.out.println("memberaction:"+memberaction);
    	System.out.println("ids:"+ids);
    	
    	String returnJSON;
    	try{
	    	//if(ids.indexOf(",")>-1){
	    	  String[] idArray = ids.split(",");
	    	  for (String id : idArray){
	    		  
	    		  if("system".equalsIgnoreCase(membertype)){
	    			  
	    			  User user = userService.getUserById(Integer.parseInt(id));
	    			  
	    			  if("Delete".equalsIgnoreCase(memberaction)){
	    				  userService.delete(user);
	    			  }else{
		    			  
			  	    	  if("Enable".equalsIgnoreCase(memberaction)){
				    		  user.setStatus("Active");
				    	  }else if("Disable".equalsIgnoreCase(memberaction)){
				    		  user.setStatus("Inactive");
				    	  }else{
				    		  throw new RuntimeException("Unsupported member action");
				    	  }
			  	    	  userService.saveUser(user);
	    			  }

	    		  }else{
	    			  
	    			  Member member = memberService.getMember(Integer.parseInt(id));
	  	    		  if("Enable".equalsIgnoreCase(memberaction)){
	  	    		      member.setStatus("Active");
	  	    		  }else if("Disable".equalsIgnoreCase(memberaction)){
	  	    			  member.setStatus("Inactive");
	  	    		  }else{
	  	    			  throw new RuntimeException("Unsupported member action");
	  	    		  }
	  	    		  memberService.saveMember(member);
	    		  }
	    		
	    	  }
	    	//}
    	}catch(Exception e){
    		log.error("Failed to update member status");
    		response.setCharacterEncoding(Constants.ENCODING_UTF8);
            try {
				response.getWriter().print(JSONObject.fromObject(new Message(e.getMessage())));
			} catch (IOException ioe) {
				log.error(""+ioe);
			}
    	}
    }
    
    @RequestMapping(value="/admin/product/query", method=RequestMethod.GET)
    public String productQuery(Model model){
    	List<Product> list = productService.listAll();
    	model.addAttribute("products", list);
    	return "admin/product/list";
    }
    
    @RequestMapping(value="/admin/product/edit", method=RequestMethod.GET)
    public String productEdit(WebRequest request, Model model){
    	String productId = request.getParameter("id");
    	String action = request.getParameter("action");
    	System.out.println("id:"+productId);
    	
    	if("update".equalsIgnoreCase(action)){
        	Product product = productService.getProduct(Integer.parseInt(productId));
        	model.addAttribute("product",product);
    	}else{
    		model.addAttribute("product",new Product());
    	}
    	
    	return "admin/product/update";
    }
    
    @RequestMapping(value="/admin/product/update", method=RequestMethod.GET)
    public String productUpdate(Model model){
    	return null;
    }
    
    @RequestMapping(value="/admin/product/promote", method=RequestMethod.GET)
    public String productPromote(WebRequest request, Model model){
    	String productId = request.getParameter("id");
    	String action = request.getParameter("action");
    	System.out.println("id:"+productId+"|action:"+action);
    	
    	if("promote".equalsIgnoreCase(action)){
    		Product product = productService.getProduct(Integer.parseInt(productId));
    		product.setPromoteIndicator("YES");
    		productService.save(product);
    	}else if("unpromote".equalsIgnoreCase(action)){
    		Product product = productService.getProduct(Integer.parseInt(productId));
    		product.setPromoteIndicator("NO");
    		productService.save(product);
    	}
    	
    	return "redirect:/admin/product/query";
    }
    
    @RequestMapping(value="/admin/product/delete", method=RequestMethod.GET)
    public String productDelete(WebRequest request, Model model){
    	String productId = request.getParameter("id");
    	String action = request.getParameter("action");
    	System.out.println("id:"+productId+"|action:"+action);
    	
    	Product product = productService.getProduct(Integer.parseInt(productId));
    	productService.deleteProduct(product);
    	
    	return "redirect:/admin/product/query";
    }
    
    @RequestMapping(value="/admin/user/update", method=RequestMethod.POST)
    public String userUpdate(User user, Model model){
    	
    	user.setCreateUser("SYSTEM");
    	user.setStatus("Active");
    	user.setCreateDate(new Date());
    	userService.saveUser(user);
    	
    	return "admin/member/systemUser";
    }
}